package com.chezai.client.global;

import android.content.Context;

import com.aliyun.sls.android.sdk.ClientConfiguration;
import com.aliyun.sls.android.sdk.LOGClient;
import com.aliyun.sls.android.sdk.LogException;
import com.aliyun.sls.android.sdk.SLSLog;
import com.aliyun.sls.android.sdk.core.auth.PlainTextAKSKCredentialProvider;
import com.aliyun.sls.android.sdk.core.callback.CompletedCallback;
import com.aliyun.sls.android.sdk.model.Log;
import com.aliyun.sls.android.sdk.model.LogGroup;
import com.aliyun.sls.android.sdk.request.PostLogRequest;
import com.aliyun.sls.android.sdk.result.PostLogResult;
import com.chezai.client.server.util.TransmissionMessageUtil;
import com.chezai.client.utils.Util;
import com.jx.driving.message.TimeTerminalTransmissionMessage;
import com.jx.driving.request.Terminal0x0102Request;
import com.jx.driving.request.Terminal0x0900Request;
import com.jx.driving.transmission.Terminal0x0306Transmission;
import com.orhanobut.logger.Logger;

/**
 * Created by likunyang on 2017/10/20.
 */

public class LogService {
    private static final String SERVICE_ENDPOINT = "cn-beijing.log.aliyuncs.com";
    private static final String A_KEY_ID = "LTAIx6nZPvbbyVH6";
    private static final String A_KEY_SECRE = "ufx0LQhge0oENzKmiCxvBNFjo1B0tH";
    private static final String PROJECT_NAME = "bj1580-terminal";
    private static LogService newInstance;
    private static boolean isOpen = false;
    private final LOGClient myClient;

    private final TransmissionMessageUtil messageUtil;
    public String REQUEST_KEY = "";
    public String RESPONE_KEY = "";

    private LogService(Context ctx) {
        messageUtil = new TransmissionMessageUtil();
        PlainTextAKSKCredentialProvider credentialProvider = new PlainTextAKSKCredentialProvider(A_KEY_ID, A_KEY_SECRE);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        conf.setCachable(false);
        conf.setConnectType(ClientConfiguration.NetworkPolicy.WWAN_OR_WIFI);
        SLSLog.disableLog();
        myClient = new LOGClient(ctx, SERVICE_ENDPOINT, credentialProvider, conf);

        String imei = DeviceFactory.getInstance().getHardware().getImei(TerminalApplication.mContext);
        REQUEST_KEY = "Request/" + imei;
        RESPONE_KEY = "Response/" + imei;

    }

    public static LogService getInstance(Context ctx) {
        if (newInstance == null) {
            newInstance = new LogService(ctx);
        }
        return newInstance;
    }

    public static boolean isOpen() {
        return isOpen;
    }

    public static void setOpen(boolean open) {
        isOpen = open;
    }

    public void putLogContent(String key, String value, boolean isOpen) {
        if (isOpen) {
            Log log = new Log();
            log.PutContent(key, value);
            LogGroup logGroup = new LogGroup("termianl", "terminal");
            logGroup.PutLog(log);
            postLog(logGroup);
        }
    }

    private void postLog(final LogGroup logGroup) {
        try {
            Logger.t("LogService").d(logGroup.LogGroupToJsonString());
            PostLogRequest request = new PostLogRequest(PROJECT_NAME, "terminal", logGroup);
            myClient.asyncPostLog(request, new CompletedCallback<PostLogRequest, PostLogResult>() {
                @Override
                public void onSuccess(PostLogRequest request, PostLogResult result) {

                }

                @Override
                public void onFailure(PostLogRequest request, LogException exception) {

                }
            });
        } catch (LogException e) {
            e.printStackTrace();
        }
    }

    public void sendMsg(Object msg) {
        if (Util.isHaveToStringMethod(msg) && LogService.isOpen()) {
            if (msg instanceof Terminal0x0900Request) {
                Terminal0x0900Request request = (Terminal0x0900Request) msg;
                TimeTerminalTransmissionMessage realMsg = messageUtil.getTerminalTransmissionMessage(request);
                if (realMsg instanceof Terminal0x0306Transmission) {
                    LogService.getInstance(TerminalApplication.mContext).putLogContent(REQUEST_KEY, "0306", isOpen);
                } else {
                    LogService.getInstance(TerminalApplication.mContext).putLogContent(REQUEST_KEY, realMsg.toString(), isOpen);
                }
            } else if (msg instanceof Terminal0x0102Request) {
                Terminal0x0102Request ox0102 = (Terminal0x0102Request) msg;
                StringBuilder builder = new StringBuilder();
                builder.append("Terminal0x0102Request [time=").append(ox0102.getTime())
                        .append(", pass=").append(ox0102.getPass() == null ? "null" : new String(ox0102.getPass()))
                        .append("]");
                LogService.getInstance(TerminalApplication.mContext).putLogContent(REQUEST_KEY, builder.toString(), isOpen);
            } else {
                LogService.getInstance(TerminalApplication.mContext).putLogContent(REQUEST_KEY, msg.toString(), isOpen);
            }
        }
    }

    public void sendLog(String msg) {
        putLogContent(REQUEST_KEY, msg, true);
    }
}
